﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Jzy.BLL.Account;
using Jzy.Core.Common.Web;
using Jzy.Core.Common;
using Jzy.Model.Account;
using System.Web.UI.HtmlControls;
using Frame.Lib.Common;
using Frame.Lib.Web;
using Frame.Lib.Utilities;
using Frame.Lib.Core.Dict;
using Frame.Lib.Enums;
using Syncfusion.XlsIO;

namespace Jzy.Web.Account
{
    public partial class List : PageList
    {

        private AccountBO Account
        {
            get
            {
                return AccountBO.Instance<AccountBO>();
            }
        }



      

        private string StartTime
        {
            get
            {
                return Request.QueryString["StartTime"];
            }

        }

        private string EndTime
        {
            get
            {
                return Request.QueryString["EndTime"];
            }
        }

        private string PageSize
        {
            get
            {
                return Request.QueryString["PageSize"];
            }
        }
        private string IsIncome
        {
            get
            {
                return Request.QueryString["IsIncome"];
            }
        }
        private string TypeCode
        {
            get
            {
                return Request.QueryString["TypeCode"];
            }

        }
        private string Name
        {
            get
            {
                return Request.QueryString["Name"];
            }
        }
       

     

        protected void Page_Load(object sender, EventArgs e)
        {         

            if (!IsPostBack)
            {
                Pager.BindDrp(drpPager);
                drpIsIncome.Items.Add(new ListItem("收支", "-1"));
                drpIsIncome.Items.Add(new ListItem("支出", "0"));
                drpIsIncome.Items.Add(new ListItem("收入", "1"));

                if (!string.IsNullOrEmpty(IsIncome))
                {
                    drpIsIncome.SelectedValue = IsIncome;
                }

                BindType();

                if (!string.IsNullOrEmpty(this.TypeCode))
                {
                    drpType.SelectedValue = this.TypeCode;
                }

                if (!string.IsNullOrEmpty(this.PageSize))
                {
                    drpPager.SelectedValue = this.PageSize;
                }
              
                if (!string.IsNullOrEmpty(this.StartTime))
                {
                    txtStartTime.Text = this.StartTime;
                }
                if (!string.IsNullOrEmpty(this.EndTime))
                {
                    txtEndTime.Text = this.EndTime;
                }

                if (!string.IsNullOrEmpty(this.Name))
                {
                    txtName.Text = this.Name;
                }
          

                BindView();

                //CustSort.SwapSortDirection(_setting);//必须要在绑定之后
            }
            InitSelectID(hidSelectIDs);
            JSUtil.SetTableHeight("list", 145);
            AddAttr();

            this.IncludeJsFile("calendar", JsFile.Calendar);
        }

        private void BindType()
        {
            DictBO dict = new DictBO();
            if(drpIsIncome.SelectedValue == "-1")
            {
                drpType.Visible = false;
            }
            else
            {
                if (drpIsIncome.SelectedValue == "0")
                {
                    dict.BindListControl(drpType, (int)DictItem.支出类型);
                    drpType.Items.Insert(0, new ListItem("支出类型", "-1"));
                }
                else
                {
                    dict.BindListControl(drpType, (int)DictItem.收入类型);
                    drpType.Items.Insert(0, new ListItem("收入类型", "-1"));

                }
                drpType.Visible = true;
               
            }
        }

        private void AddAttr()
        {     

            WebUtil.SetTimeBox(txtStartTime, false);
            WebUtil.SetTimeBox(txtEndTime, false);

            JSUtil.DelConfirm(btnDelete, "账目记录");
            JSUtil.ClickBtn(lnkDelete, btnDelete);

            JSUtil.ShowForm(lnkIncome, "收入登记", null, GlobalVar.WebCurrPath + "Edit.aspx?IsIncome=1", 450, 261);

            JSUtil.ShowForm(lnkOut, "支出登记", null, GlobalVar.WebCurrPath + "Edit.aspx?IsIncome=0", 450, 261);

            JSUtil.ClickBtn(lnkExport, btnExport);
            
        }

        private PagerSetting GetPagerSetting()
        {
            PagerSetting setting = new PagerSetting();
            setting.PageIndex = this.PageIndex;
            setting.PageSize = int.Parse(drpPager.SelectedValue);

            setting.OrderBy = "OccurTime desc,InputTime desc";

            setting.Where = " 1=1 ";
            if (!string.IsNullOrEmpty(txtStartTime.Text.Trim()))
            {
                setting.Where += " and OccurTime>=@p0 ";
            }
            if (!string.IsNullOrEmpty(txtEndTime.Text.Trim()))
            {
                setting.Where += " and OccurTime<=@p1";
            }
            if (drpIsIncome.SelectedValue != "-1")
            {
                setting.Where += " and IsIncome=" + drpIsIncome.SelectedValue;

                if (drpType.SelectedValue != "-1")
                {
                    setting.Where += " and TypeCode = " + drpType.SelectedValue;
                }
            }
            if (txtName.Text.Trim() != "")
            {
                setting.Where += " and Name like @p2";
            }

            return setting;
        }

        private void BindView()
        {
            LVUtil.Init(lv, lvHeader);
            chkSelectAll.Checked = false;

            PagerSetting setting = GetPagerSetting();

            object[] paras = { txtStartTime.Text, txtEndTime.Text, txtName.Text };

            IEnumerable<AccountInfo> list = Account.GetList(setting, paras);

            // setting.RecordCount = 80;
            lv.DataKeyNames = new string[] { "ID" };
            lv.DataSource = list;
            lv.DataBind();

            string prefix = GlobalVar.WebCurrPath + "List.aspx?PageSize=" + drpPager.SelectedValue + "&Name=" + txtName.Text + "&StartTime=" + txtStartTime.Text + "&EndTime=" + txtEndTime.Text + "&IsIncome=" + drpIsIncome.SelectedValue + "&TypeCode=" + drpType.SelectedValue;



            litPager.Text = HtmlPager.Render(setting, prefix, true);

            decimal outAmount = Account.SumOut(setting.Where, paras);
            litOut.Text = outAmount.ToString("c");

            decimal incomeAmount = Account.SumIncome(setting.Where, paras);
            litIncome.Text = incomeAmount.ToString("c");

            decimal total = outAmount + incomeAmount;
            litTotal.Text = total.ToString("c");

            if (total < 0)
            {
                litTotal.ForeColor = System.Drawing.Color.Red;
            }
            

        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (strSelectIDs != "")
            {
                Account.Delete(StrUtil.SplitToStr(strSelectIDs));
                BindView();
            }
        }
        protected void drpPager_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindView();
        }

      

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            BindView();
        }

       

        protected void drpType_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindView();
        }

        protected void drpIsIncome_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindType();
            BindView();
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            BindView();
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {

            PagerSetting setting = GetPagerSetting();

            object[] paras = { txtStartTime.Text, txtEndTime.Text, txtName.Text };

            List<AccountInfo> list = Account.GetList(setting.Where, paras);

            string title = "类型：";
            if (drpIsIncome.SelectedValue == "-1")
            {
                title += "收支";
            }
            else
            {
                title += drpIsIncome.SelectedItem.Text;
                if (drpType.SelectedValue != "-1")
                {
                    title += "(" + drpType.SelectedItem.Text + ")";
                }
            }

            title += ",日期：" + txtStartTime.Text + "-" + txtEndTime.Text + ",关键字：" + txtName.Text;

          

            ExcelEngine engine = new ExcelEngine();
            IApplication app = engine.Excel;
            IWorkbook book = app.Workbooks.Add();
            IWorksheet sheet = book.Worksheets[0];
            sheet.PageSetup.CenterHorizontally = true;
            sheet.PageSetup.Orientation = ExcelPageOrientation.Landscape;
            sheet.PageSetup.TopMargin = 0.5;
            sheet.PageSetup.LeftMargin = 0.5;
            sheet.PageSetup.RightMargin = 0.5;

            sheet.Range[1, 1].Text = title;
            sheet.Range[1, 1].RowHeight = 15;
            sheet.Range[1, 1].ColumnWidth = 15;

            sheet.Range[2, 1].Text = "描述";
            sheet.Range[2, 1].RowHeight = 15;
           // sheet.Range[2, 1].ColumnWidth = 100;

            sheet.Range[2, 2].Text = "金额";

            sheet.Range[2, 3].Text = "发生时间";
            

            sheet.Range[2, 4].Text = "类型";

            sheet.Range[2, 5].Text = "录入员";

           

            sheet.Range[2, 1, 2, 5].CellStyle.Font.Bold = true;

            for (int i = 0; i < list.Count; i++)
            {

                sheet.Range[i + 3, 1].Text = list[i].Name;

                sheet.Range[i + 3, 2].Text = list[i].Amount.ToString();
                sheet.Range[i + 3, 3].Text = list[i].OccurTime.ToString();
                //sheet.Range[i + 3, 3].WrapText = true; 
                sheet.Range[i + 3, 4].Text = list[i].TypeName;


                sheet.Range[i + 3, 5].Text = list[i].CreatorName;
                

               // sheet.Range[i + 2, 1, i + 2, 5].VerticalAlignment = ExcelVAlign.VAlignCenter;
            }

            for (int i = 2; i < list.Count + 3; i++)
            {
                for (int j = 1; j < 6; j++)
                {
                    IRange range = sheet.Range[i, j];
                    IBorders border = range.CellStyle.Borders;

                    border.LineStyle = ExcelLineStyle.Thin;

                    border[ExcelBordersIndex.DiagonalDown].LineStyle = border[ExcelBordersIndex.DiagonalUp].LineStyle = ExcelLineStyle.None;
                }
            }

            book.SaveAs("account.xls", ExcelSaveType.SaveAsXLS, Response, ExcelDownloadType.PromptDialog);
        }

        protected void lv_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                AccountInfo info = (e.Item as ListViewDataItem).DataItem as AccountInfo;
                string url = GlobalVar.WebCurrPath + "Edit.aspx?IsIncome=" + (info.IsIncome ? "1" : "0");
                LVUtil.SetEdit(sender, e, 450, 261,url);

                HtmlTableRow row = e.Item.FindControl("row") as HtmlTableRow;
               
                if (!info.IsIncome)
                {
                    row.Style.Add("color", "Red");

                }
            }
        }
    }
}